package tuxinjiemian;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JisuanqiBuju extends JFrame implements ActionListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField tf;
	private JButton clcer;
	private boolean isNew=true;
	private double result=0;
	private String preOperator="+";
	public JisuanqiBuju() {
		setSize(500, 500);
		setLocation(700,200);//显示位置
		setVisible(true);// 显示窗体
		setTitle("计算器界面");
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		Font font = new Font("微软雅黑", Font.TRUETYPE_FONT, 36);

		JPanel top = new JPanel(new BorderLayout());
		clcer = new JButton("清除");
		clcer.addActionListener(this);
		clcer.setFont(font);
		top.add(clcer, BorderLayout.EAST);

		tf = new JTextField("0");
		tf.setHorizontalAlignment(JTextField.RIGHT);//设置文本对齐
		tf.setEditable(false);//设置编辑框
		tf.setDisabledTextColor(Color.BLUE);
		tf.setFont(font);
		top.add(tf, BorderLayout.CENTER);
		
		add(top, BorderLayout.NORTH);

		JPanel center = new JPanel(new GridLayout(4, 4));
		String[] str = { "7", "8", "9", "+", 
						 "4", "5", "6", "-", 
						 "1", "2", "3", "*", 
						 "0", ".", "=", "/" };
		for (String s : str) {
			JButton bt = new JButton(s);
			bt.setFont(font);
			bt.setBackground(Color.WHITE);
			bt.setForeground(new Color(0x00000));//设置前景色
			bt.addActionListener(this);
			center.add(bt);
		}
		add(center, BorderLayout.CENTER);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			// 写个内部内来实现输入窗口
			@Override
			public void run() {
				new JisuanqiBuju();
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String acmd =e.getActionCommand();		
		if("0.123456789".indexOf(acmd)>=0){						
			numInput(acmd);}
		else if(acmd.equals("清除"))
		tf.setText("0");
		else{
			calculator(acmd);
		}
	
	}

	private void calculator(String op) {
		isNew=true;
		double num=Double.valueOf(tf.getText());
		switch(preOperator){
		case "+":result+=num; break;
		case "-":result-=num; break;
		case "*":result*=num; break;
		case "/":result/=num; break;
		}
		String str=String.valueOf(result);
		if(str.endsWith(".0")){
			str=str.substring(0, str.length()-2);
		}
		tf.setText(str);
		preOperator=op;
	}

	private void numInput(String num) {
		String yuan=tf.getText();
		if(isNew) yuan="0";
		if(yuan.equals("0")){
			isNew=false;
			if(!num.equals("0")){
				if(num.equals("."))tf.setText("0.");
				else tf.setText(num);
				return;
			}
		}
		else{
			if(yuan.indexOf(".")>=0&&num.equals("."))
				return;
			tf.setText(yuan+num);	
		}
	}
}
